import axios from "axios";
import { notification } from "ant-design-vue";
import { axiosConfig } from "../../config";
import store from "../../store";
import router from "../../router/index";

interface ResponseDataType {
    code: number;
    message: string;
    description?: string;
}

const handleCode = (data: ResponseDataType) => {
    notification["error"]({
        message: data.message,
        description: data.description,
    });
};

const handleError = (data: { message: string }) => {
    notification["error"]({
        message: "系统异常",
        description: data.message,
    });
};

const instance = axios.create({
    baseURL: axiosConfig.baseURL,
    timeout: axiosConfig.timeout,
    headers: {
        "Content-Type": axiosConfig.contentType,
    },
});
instance.interceptors.request.use(
    (config) => {
        store.dispatch("loading/addLoadingAction");
        const token = sessionStorage.getItem("token");
        if (token) config.headers.Authorization = "Bearer " + token;
        return config;
    },
    (error) => {
        console.log(error);
        return Promise.reject(error);
    }
);
instance.interceptors.response.use(
    (response) => {
        store.dispatch("loading/subLoadingAction");
        if (response.data.message == "用户未登陆") {
            router.push("/login");
            return false;
        }
        const { code } = response.data;
        if (code === 0) {
            notification["success"]({
                message: response.data.message,
            });
            return response.data;
        } else if (code === 10000) {
            handleCode(response.data);
            if (location.pathname != "/login") {
                router.push("/login");
            }
            return Promise.reject(response.data);
        } else {
            handleCode(response.data);
            return Promise.reject(response.data);
        }
    },
    (error) => {
        console.log(error);
        store.dispatch("loading/subLoadingAction");
        const { response } = error;
        if (error.response && error.response.data) {
            handleCode(response.data);
            return Promise.reject(error);
        } else {
            let { message } = error;
            handleError({ message: message });
            return Promise.reject(error);
        }
    }
);

export default instance;
